from datetime import datetime

from app1 import db  # 导入 SQLAlchemy 实例

from sqlalchemy.dialects.mysql import BIGINT


class Zbfwbuser(db.Model):
    __tablename__ = 't_zbfwb_user'  # 指定表名，可选

    t_zbfwb_user_id = db.Column(db.Integer, primary_key=True)
    t_zbfwb_user_name = db.Column(db.String(255), unique=True, nullable=False)
    t_zbfwb_user_passwd = db.Column(db.String(255), nullable=False)
    t_zbfwb_user_createtime = db.Column(db.DateTime, default=db.func.current_timestamp())
    t_zbfwb_user_updatetime = db.Column(db.DateTime, default=db.func.current_timestamp(),
                                        onupdate=db.func.current_timestamp())

    def __init__(self, t_zbfwb_user_id, t_zbfwb_user_name, t_zbfwb_user_passwd):
        self.t_zbfwb_user_id = t_zbfwb_user_id
        self.t_zbfwb_user_name = t_zbfwb_user_name
        self.t_zbfwb_user_passwd = t_zbfwb_user_passwd
        # 可选：在初始化时设置其他字段的默认值

    # 可选：定义其他方法或属性
    def to_dict(self):
        """将模型实例转换为字典"""
        return {
            't_zbfwb_user_id': self.t_zbfwb_user_id,
            't_zbfwb_user_name': self.t_zbfwb_user_name,
            't_zbfwb_user_passwd': self.t_zbfwb_user_passwd,
            't_zbfwb_user_createtime': self.t_zbfwb_user_createtime,
            't_zbfwb_user_updatetime': self.t_zbfwb_user_updatetime
        }


# 注意：本模型使用 zbfwb_role_name 作为主键
# 查询ID必须用 filter_by(zbfwb_role_id=...)
class Zbfwbrole(db.Model):
    __tablename__ = 't_zbfwb_role'  # 指定表名，可选

    zbfwb_role_id = db.Column(db.Integer, nullable=False)
    zbfwb_role_name = db.Column(db.String(255), unique=True, primary_key=True)
    zbfwb_role_title = db.Column(db.String(255))
    zbfwb_role_createtime = db.Column(db.DateTime, default=db.func.current_timestamp())
    zbfwb_role_updatetime = db.Column(db.DateTime, default=db.func.current_timestamp())

    def __init__(self, zbfwb_role_id, zbfwb_role_name, zbfwb_role_title):
        self.zbfwb_role_id = zbfwb_role_id
        self.zbfwb_role_name = zbfwb_role_name
        self.zbfwb_role_title = zbfwb_role_title
        # 可选：在初始化时设置其他字段的默认值

    def to_dict(self):
        """将模型实例转换为字典"""
        return {
            'zbfwb_role_id': self.zbfwb_role_id,
            'zbfwb_role_name': self.zbfwb_role_name,
            'zbfwb_role_title': self.zbfwb_role_title,
            'zbfwb_role_createtime': self.zbfwb_role_createtime,
            'zbfwb_role_updatetime': self.zbfwb_role_updatetime
        }


class Zbfwbuserrole(db.Model):
    __tablename__ = 't_zbfwb_user_role'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    uid = db.Column(db.Integer, db.ForeignKey('t_zbfwb_user.t_zbfwb_user_id'), nullable=False)
    rid = db.Column(db.Integer, db.ForeignKey('t_zbfwb_role.zbfwb_role_id'), nullable=True)
    desc = db.Column(db.String(255))
    create_time = db.Column(db.DateTime, default=db.func.current_timestamp())
    update_time = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp())

    # 关联字段
    user = db.relationship('Zbfwbuser', backref=db.backref('user_roles', lazy='dynamic'))
    role = db.relationship('Zbfwbrole', backref=db.backref('role_users', lazy='dynamic'))

    def __init__(self, uid, rid, desc=None):
        self.uid = uid
        self.rid = rid
        self.desc = desc

    def to_dict(self):
        """将模型实例转换为字典"""
        return {
            'id': self.id,
            'uid': self.uid,
            'rid': self.rid,
            'desc': self.desc,
            'create_time': self.create_time,
            'update_time': self.update_time,
            'user': self.user.to_dict() if self.user else None,
            'role': self.role.to_dict() if self.role else None
        }


class Zbfwbperm(db.Model):
    __tablename__ = 't_zbfwb_perm'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    per_name = db.Column(db.String(255))
    perm_code = db.Column(db.Integer, unique=True)
    perm_op = db.Column(db.String(255))
    perm_ob = db.Column(db.String(255))
    create_time = db.Column(db.DateTime, default=db.func.current_timestamp())
    update_time = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp())

    def __init__(self, per_name, perm_code, perm_op, perm_ob):
        self.per_name = per_name
        self.perm_code = perm_code
        self.perm_op = perm_op
        self.perm_ob = perm_ob

    def to_dict(self):
        """将模型实例转换为字典"""
        return {
            'id': self.id,
            'per_name': self.per_name,
            'perm_code': self.perm_code,
            'perm_op': self.perm_op,
            'perm_ob': self.perm_ob,
            'create_time': self.create_time,
            'update_time': self.update_time
        }


class Zbfwbroleperm(db.Model):
    __tablename__ = 't_zbfwb_role_perm'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    rid = db.Column(db.Integer, db.ForeignKey('t_zbfwb_role.zbfwb_role_id'), nullable=True)
    pid = db.Column(db.Integer, db.ForeignKey('t_zbfwb_perm.id'), nullable=True)
    desc = db.Column(db.String(255))
    create_time = db.Column(db.DateTime, default=db.func.current_timestamp())
    update_time = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp())

    # 关联字段
    role = db.relationship('Zbfwbrole', backref=db.backref('role_permissions', lazy='dynamic'))
    perm = db.relationship('Zbfwbperm', backref=db.backref('perm_roles', lazy='dynamic'))

    def __init__(self, rid, pid, desc=None):
        self.rid = rid
        self.pid = pid
        self.desc = desc

    def to_dict(self):
        """将模型实例转换为字典"""
        return {
            'id': self.id,
            'rid': self.rid,
            'pid': self.pid,
            'desc': self.desc,
            'create_time': self.create_time,
            'update_time': self.update_time,
            'role': self.role.to_dict() if self.role else None,
            'perm': self.perm.to_dict() if self.perm else None
        }


class Zbfwb_tb_alarm(db.Model):
    __tablename__ = 'tb_alarm'  # 指定表名，可选

    seq_num = db.Column(db.String(20), nullable=False, primary_key=True)
    occurrence_time = db.Column(db.DateTime, default=db.func.current_timestamp())
    sys_name = db.Column(db.String(100))
    dev_addr = db.Column(db.String(100))
    info = db.Column(db.Text)
    keyword = db.Column(db.String(255))
    repeat_times = db.Column(db.Integer)
    last_update_time = db.Column(db.DateTime, default=db.func.current_timestamp())
    level = db.Column(db.String(20))
    kms_count = db.Column(db.Integer)
    kms_id = db.Column(db.Integer)
    # tb_alarm_createtime = db.Column(db.DateTime, default=db.func.current_timestamp())
    # tb_alarm_updatetime = db.Column(db.DateTime, default=db.func.current_timestamp())


# -- ----------------------------
# -- Table structure for kms_alarm
# -- ----------------------------
# DROP TABLE IF EXISTS `kms_alarm`;
# CREATE TABLE `kms_alarm`  (
#   `seq_num` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '告警序号',
#   `occurrence_time` datetime(6) NULL DEFAULT NULL COMMENT '告警发生时间',
#   `sys_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '系统名称',
#   `service_catalog` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '服务目录编号',
#   `dev_addr` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'IP地址',
#   `info` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '告警内容',
#   `keyword` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL COMMENT '关键字',
#   `repeat_times` int NULL DEFAULT NULL COMMENT '重复次数',
#   `level` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '告警级别',
#   `status` int NULL DEFAULT 0 COMMENT '状态（0未处置，1已处置）',
#   `kms_count` int NULL DEFAULT 0 COMMENT '知识匹配计数',
#   `kms_id` int NULL DEFAULT NULL COMMENT '知识ID',
#   `is_change_related` int NULL DEFAULT NULL COMMENT '是否变更引起（0否、1是）',
#   `is_report` int NULL DEFAULT NULL COMMENT '是否举手（0否、1是）',
#   `actual_cause` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '实际原因',
#   `action_type` int NULL DEFAULT NULL COMMENT '处置类别（0无需处置、1 值班处置、2二线处置）',
#   `action` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '处置措施',
#   `create_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '创建者',
#   `create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
#   `update_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '更新者',
#   `update_time` datetime NULL DEFAULT NULL COMMENT '更新时间',
#   `remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '备注',
#   PRIMARY KEY (`seq_num`) USING BTREE,
#   INDEX `occurrence_time`(`occurrence_time` ASC) USING BTREE,
#   INDEX `keyword`(`keyword` ASC) USING BTREE,
#   INDEX `sys_name`(`sys_name` ASC) USING BTREE
# ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;
#
# SET FOREIGN_KEY_CHECKS = 1;


class Zbfwb_kms_alarm(db.Model):
    __tablename__ = 'kms_alarm'  # 指定表名，可选

    seq_num = db.Column(db.String(20), nullable=False, primary_key=True)  #告警序号
    occurrence_time = db.Column(db.DateTime, default=db.func.current_timestamp())  #告警发生时间
    sys_name = db.Column(db.String(100))  #系统名称
    service_catalog = db.Column(db.String(20))  #服务目录编号
    dev_addr = db.Column(db.String(100))  #IP地址
    info = db.Column(db.Text)  #告警内容
    keyword = db.Column(db.String(255))  #关键字
    repeat_times = db.Column(db.Integer)  #重复次
    level = db.Column(db.String(20))  #告警级别
    status = db.Column(db.Integer)  #状态（0未处置，1已处置）
    kms_count = db.Column(db.Integer)  #知识匹配计数
    kms_id = db.Column(db.Integer)  #知识ID
    is_change_related = db.Column(db.Integer)  #'是否变更引起（0否、1是）',
    is_report = db.Column(db.Integer)  #'是否举手（0否、1是）',
    actual_cause = db.Column(db.String(500))  #'实际原因',
    action_type = db.Column(db.Integer)  #'处置类别（0无需处置、1 值班处置、2二线处置）',
    action = db.Column(db.String(500))  #'处置措施',
    create_by = db.Column(db.String(64))  #'创建者',
    create_time = db.Column(db.DateTime, default=db.func.current_timestamp())  #'创建时间',
    update_by = db.Column(db.String(64))  #'更新者',
    update_time = db.Column(db.DateTime, default=db.func.current_timestamp())  #'更新时间',
    remark = db.Column(db.String(500))  #'备注',

    def to_dict(self):
        return {
            'seq_num': self.seq_num,
            'occurrence_time': self.occurrence_time,
            'sys_name': self.sys_name,
            'service_catalog': self.service_catalog,
            'dev_addr': self.dev_addr,
            'info': self.info,
            'keyword': self.keyword,
            'repeat_times': self.repeat_times,
            'level': self.level,
            'status': self.status,
            'kms_count': self.kms_count,
            'kms_id': self.kms_id,
            'is_change_related': self.is_change_related,
            'is_report': self.is_report,
            'actual_cause': self.actual_cause,
            'action_type': self.action_type,
            'action': self.action,
            'create_by': self.create_by,
            'create_time': self.create_time,
            'update_by': self.update_by,
            'update_time': self.update_time,
            'remark': self.remark
        }


class Zbfwb_RemedyGongdan_old(db.Model):
    __tablename__ = 'remedy_gongdan_old'  # 指定表名

    TicketID = db.Column(db.String(60), primary_key=True, nullable=False)  # 工单编号
    SRMType = db.Column(db.String(254), nullable=False)  # 工单类型
    Cer1 = db.Column(db.String(255), nullable=False)  # 证书1
    Cer2 = db.Column(db.String(255), nullable=False)  # 证书2
    Cer3 = db.Column(db.String(255), nullable=False)  # 证书3
    Status = db.Column(db.String(50))  # 状态
    StatusReason = db.Column(db.String(40))  # 状态原因
    SystemName = db.Column(db.String(254))  # 系统名称
    Decription = db.Column(db.Text)  # 描述
    SupportCompany = db.Column(db.String(255))  # 支持公司
    AssignedGroup = db.Column(db.String(60))  # 分配组
    Assignee = db.Column(db.String(69))  # 分配人
    Submiter = db.Column(db.String(80))  # 提交人
    Customer = db.Column(db.String(255))  # 客户
    ContactCompany = db.Column(db.String(255))  # 联系公司
    Organization = db.Column(db.String(255))  # 组织
    Department = db.Column(db.String(255))  # 部门
    CreateTime = db.Column(db.DateTime)  # 创建时间
    SolveTime = db.Column(db.DateTime)  # 解决时间
    RecTime = db.Column(db.DateTime)  # 接收时间
    SendHx = db.Column(db.String(1))  # 是否发送hx

    def to_dict(self):
        return {
            'TicketID': self.TicketID,
            'SRMType': self.SRMType,
            'Cer1': self.Cer1,
            'Cer2': self.Cer2,
            'Cer3': self.Cer3,
            'Status': self.Status,
            'StatusReason': self.StatusReason,
            'SystemName': self.SystemName,
            'Description': self.Description,
            'SupportCompany': self.SupportCompany,
            'AssignedGroup': self.AssignedGroup,
            'Assignee': self.Assignee,
            'Submiter': self.Submiter,
            'Customer': self.Customer,
            'ContactCompany': self.ContactCompany,
            'Organization': self.Organization,
            'Department': self.Department,
            'CreateTime': self.CreateTime,
            'SolveTime': self.SolveTime,
            'RecTime': self.RecTime,
            'SendHx': self.SendHx
        }


class Zbfwb_RemedyGongdan(db.Model):
    __tablename__ = 'remedy_gongdan'  # 指定表名

    TicketID = db.Column(db.String(60), primary_key=True, nullable=False)  # 工单编号
    SRMType = db.Column(db.String(254), nullable=False)  # 工单类型
    Chr_Cer1 = db.Column(db.String(255), nullable=False)  # 证书1
    Chr_Cer2 = db.Column(db.String(255), nullable=False)  # 证书2
    Chr_Cer3 = db.Column(db.String(255), default=None)  # 证书3
    Chr_SRM_Status = db.Column(db.String(50), default=None)  # 状态
    Status_Reason = db.Column(db.String(40), default=None)  # 状态原因
    SystemName = db.Column(db.String(254), default=None)  # 系统名称
    Detailed_Decription = db.Column(db.Text, default=None)  # 描述
    Assigned_Support_Company = db.Column(db.String(255), default=None)  # 支持公司
    Assigned_Group = db.Column(db.String(60), default=None)  # 分配组
    Assignee = db.Column(db.String(69), default=None)  # 分配人
    Submiter = db.Column(db.String(80), default=None)  # 提交人
    Customer = db.Column(db.String(255), default=None)  # 客户
    Contact_Company = db.Column(db.String(255), default=None)  # 联系公司
    Organization = db.Column(db.String(255), default=None)  # 组织
    Department = db.Column(db.String(255), default=None)  # 部门
    CreateTime = db.Column(db.DateTime, default=None)  # 创建时间
    SolveTime = db.Column(db.DateTime, default=None)  # 解决时间
    Priority = db.Column(db.String(20), default=None)  # 优先级
    cDat_AppTime = db.Column(db.DateTime, default=None)  # 应用时间
    cDat_EccalastTime = db.Column(db.DateTime, default=None)  # 最近更新时间
    cSel_EsclationYN = db.Column(db.String(20), default=None)  # 是否升级
    RecTime = db.Column(db.DateTime, default=None)  # 接收时间
    SendHx = db.Column(db.String(1), default=None)  # 是否发送hx

    def to_dict(self):
        return {
            'TicketID': self.TicketID,
            'SRMType': self.SRMType,
            'Chr_Cer1': self.Chr_Cer1,
            'Chr_Cer2': self.Chr_Cer2,
            'Chr_Cer3': self.Chr_Cer3,
            'Chr_SRM_Status': self.Chr_SRM_Status,
            'Status_Reason': self.Status_Reason,
            'SystemName': self.SystemName,
            'Detailed_Decription': self.Detailed_Decription,
            'Assigned_Support_Company': self.Assigned_Support_Company,
            'Assigned_Group': self.Assigned_Group,
            'Assignee': self.Assignee,
            'Submiter': self.Submiter,
            'Customer': self.Customer,
            'Contact_Company': self.Contact_Company,
            'Organization': self.Organization,
            'Department': self.Department,
            'CreateTime': self.CreateTime,
            'SolveTime': self.SolveTime,
            'Priority': self.Priority,
            'cDat_AppTime': self.cDat_AppTime,
            'cDat_EccalastTime': self.cDat_EccalastTime,
            'cSel_EsclationYN': self.cSel_EsclationYN,
            'RecTime': self.RecTime,
            'SendHx': self.SendHx
        }


# -- ----------------------------
# -- Table structure for machine_cmdb
# -- ----------------------------
# DROP TABLE IF EXISTS `machine_cmdb`;
# CREATE TABLE `machine_cmdb` (
#   `source` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '来源',
#   `machine_type` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '服务器类型',
#   `service_catalog` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '服务目录编号',
#   `app_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '系统名',
#   `project_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '项目名',
#   `app_abbre` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '系统简称',
#   `availability_level` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '可用性等级',
#   `dr_level` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '灾备等级',
#   `machine_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '主机名',
#   `ip` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT 'IP',
#   `dmz_ip` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT 'DMZ内网IP',
#   `data_center` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '数据中心',
#   `network_area` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '网络区域',
#   `resource_pool` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '资源池',
#   `host_machine` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '宿主机信息',
#   `physical_machine` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '物理机序列号',
#   `server_type` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '服务器角色',
#   `os_level` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '操作系统版本',
#   `middleware` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '中间件',
#   `status` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '状态',
#   `online_time` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '上线时间',
#   `run_status` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '运行状态',
#   `rec_date` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT '录入时间',
#   `role_a` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT 'A角',
#   `role_b` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT 'B角',
#   `role_c` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL COMMENT 'C角'
# ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='生产全量服务器列表';

class Zbfwb_machine_cmdb(db.Model):
    __tablename__ = 'machine_cmdb'  # 指定表名

    source = db.Column(db.String(30), nullable=False)  # 来源
    machine_type = db.Column(db.String(30), nullable=False)  # 服务器类型
    service_catalog = db.Column(db.String(30), nullable=False)  # 服务目录编号
    app_name = db.Column(db.String(100), nullable=False)  # 系统名
    project_name = db.Column(db.String(100), nullable=False)  # 项目名
    app_abbre = db.Column(db.String(100), nullable=False)  # 系统简称
    availability_level = db.Column(db.String(20), nullable=False)  # 可用性等级
    dr_level = db.Column(db.String(20), nullable=False)  # 灾备等级
    machine_name = db.Column(db.String(100), primary_key=True, nullable=False)  # 主机名
    ip = db.Column(db.String(50), primary_key=True, nullable=False)  # IP
    dmz_ip = db.Column(db.String(50), nullable=False)  # DMZ内网IP
    data_center = db.Column(db.String(50), nullable=False)  # 数据中心
    network_area = db.Column(db.String(200), nullable=False)  # 网络区域
    resource_pool = db.Column(db.String(200), nullable=False)  # 资源池
    host_machine = db.Column(db.String(100), nullable=False)  # 宿主机信息
    physical_machine = db.Column(db.String(200), nullable=False)  # 物理机序列号
    server_type = db.Column(db.String(100), nullable=False)  # 服务器角色
    os_level = db.Column(db.String(200), nullable=False)  # 操作系统版本
    middleware = db.Column(db.String(500), nullable=False)  # 中间件
    status = db.Column(db.String(50), nullable=False)  # 状态
    online_time = db.Column(db.String(50), nullable=False)  # 上线时间
    run_status = db.Column(db.String(50), nullable=False)  # 运行状态
    rec_date = db.Column(db.String(50), nullable=False)  # 录入时间
    role_a = db.Column(db.String(20), nullable=False)  # A角
    role_b = db.Column(db.String(20), nullable=False)  # B角
    role_c = db.Column(db.String(20), nullable=False)  # C角

    def to_dict(self):
        return {
            'source': self.source,
            'machine_type': self.machine_type,
            'service_catalog': self.service_catalog,
            'app_name': self.app_name,
            'project_name': self.project_name,
            'app_abbre': self.app_abbre,
            'availability_level': self.availability_level,
            'dr_level': self.dr_level,
            'machine_name': self.machine_name,
            'ip': self.ip,
            'dmz_ip': self.dmz_ip,
            'data_center': self.data_center,
            'network_area': self.network_area,
            'resource_pool': self.resource_pool,
            'host_machine': self.host_machine,
            'physical_machine': self.physical_machine,
            'server_type': self.server_type,
            'os_level': self.os_level,
            'middleware': self.middleware,
            'status': self.status,
            'online_time': self.online_time,
            'run_status': self.run_status,
            'rec_date': self.rec_date,
            'role_a': self.role_a,
            'role_b': self.role_b,
            'role_c': self.role_c
        }

    def __repr__(self):
        return f'<Zbfwb_machine_cmdb {self.machine_name}>'


# biangeng
class Zbfwb_RemedyBiangeng(db.Model):
    __tablename__ = 'remedy_biangeng'

    TicketID = db.Column(db.String(60), primary_key=True, nullable=False)
    Change_Request_Status = db.Column(db.Integer, nullable=True)
    StatusDescription = db.Column(db.String(255), nullable=True)
    RequestType = db.Column(db.Integer, nullable=True)
    CHGName = db.Column(db.String(1000), nullable=True)
    Reason = db.Column(db.String(5000), nullable=True)
    ChangeType = db.Column(db.Integer, nullable=True)
    ChangeType2 = db.Column(db.String(60), nullable=True)
    EvnType = db.Column(db.Integer, nullable=True)
    Batch = db.Column(db.String(60), nullable=True)
    Categorization_Tier_4 = db.Column(db.String(60), nullable=True)
    ChangeRange = db.Column(db.String(500), nullable=True)
    StartDate = db.Column(db.DateTime, nullable=True)
    EndDate = db.Column(db.DateTime, nullable=True)
    ImpactMonitor = db.Column(db.Integer, nullable=True)
    Last_Name = db.Column(db.String(600), nullable=True)
    Department = db.Column(db.String(600), nullable=True)
    ASCHG = db.Column(db.String(600), nullable=True)
    ASGRP = db.Column(db.String(600), nullable=True)
    RecTime = db.Column(db.DateTime, nullable=True)
    SendHx = db.Column(db.String(1), nullable=True)

    def __repr__(self):
        return f"<RemedyBiangeng TicketID={self.TicketID}>"

    def to_dict(self):
        """将模型实例转换为字典格式"""
        return {
            'TicketID': self.TicketID,
            'Change_Request_Status': self.Change_Request_Status,
            'StatusDescription': self.StatusDescription,
            'RequestType': self.RequestType,
            'CHGName': self.CHGName,
            'Reason': self.Reason,
            'ChangeType': self.ChangeType,
            'ChangeType2': self.ChangeType2,
            'EvnType': self.EvnType,
            'Batch': self.Batch,
            'Categorization_Tier_4': self.Categorization_Tier_4,
            'ChangeRange': self.ChangeRange,
            'StartDate': self.StartDate.strftime('%Y-%m-%d %H:%M:%S') if self.StartDate else None,
            'EndDate': self.EndDate.strftime('%Y-%m-%d %H:%M:%S') if self.EndDate else None,
            'ImpactMonitor': self.ImpactMonitor,
            'Last_Name': self.Last_Name,
            'Department': self.Department,
            'ASCHG': self.ASCHG,
            'ASGRP': self.ASGRP,
            'RecTime': self.RecTime.strftime('%Y-%m-%d %H:%M:%S') if self.RecTime else None,
            'SendHx': self.SendHx
        }


# 说明
# 字段定义：
# 按照数据库表定义映射字段，包括字段名、类型、是否允许为空、默认值和注释。
# __repr__ 方法：
# 提供一个简单的字符串表示以便调试。
# to_dict 方法：
# 用于将模型实例转换为字典，方便在接口中返回 JSON 数据。
# 索引：
# 表中的索引（如 alarm_alias 和 service_catalog 等）不需要显式声明，SQLAlchemy 会自动识别数据库中已存在的索引。

# 应用信息列表
class KmsAppInfo(db.Model):
    __tablename__ = 'kms_app_info'

    service_catalog = db.Column(db.String(50), primary_key=True, nullable=False, comment='服务目录编号')
    service_name = db.Column(db.String(100), nullable=False, comment='服务名')
    en_short_name = db.Column(db.String(50), primary_key=True, nullable=False, comment='英文简称')
    alarm_alias = db.Column(db.String(500), nullable=False, comment='告警别名')
    role_a = db.Column(db.String(100), nullable=False, comment='A角')
    role_b = db.Column(db.String(100), nullable=False, comment='B角')
    ha_grade = db.Column(db.String(50), nullable=False, comment='可用性级别')
    dr_grade = db.Column(db.String(50), nullable=False, comment='灾备级别')
    service_time = db.Column(db.String(50), nullable=False, comment='服务时间')
    system_platform = db.Column(db.String(50), nullable=False, comment='系统平台')
    dev_org = db.Column(db.String(50), nullable=False, comment='开发单位')
    importance_grade = db.Column(db.String(50), nullable=False, comment='重要性分级')
    developer = db.Column(db.String(255), nullable=True, default=None, comment='开发项目组')

    def __repr__(self):
        return f"<KmsAppInfo service_catalog={self.service_catalog}, service_name={self.service_name}>"

    def to_dict(self):
        """将模型实例转换为字典格式"""
        return {
            'service_catalog': self.service_catalog,
            'service_name': self.service_name,
            'en_short_name': self.en_short_name,
            'alarm_alias': self.alarm_alias,
            'role_a': self.role_a,
            'role_b': self.role_b,
            'ha_grade': self.ha_grade,
            'dr_grade': self.dr_grade,
            'service_time': self.service_time,
            'system_platform': self.system_platform,
            'dev_org': self.dev_org,
            'importance_grade': self.importance_grade,
            'developer': self.developer,
        }


class StaffInfo(db.Model):
    __tablename__ = 'staff_info'

    id = db.Column(db.Integer, autoincrement=True, nullable=False, comment='Serial Number')
    name = db.Column(db.String(255), nullable=False, comment='Name')
    gender = db.Column(db.String(255), nullable=False, comment='Gender')
    employee_id = db.Column(db.String(255), primary_key=True, nullable=False, comment='Employee ID')
    id_card = db.Column(db.String(255), nullable=False, comment='Identity Card Number')
    contact = db.Column(db.String(255), nullable=False, comment='Contact Information')
    dev_dept = db.Column(db.String(255), nullable=False, comment='Development Department')
    team = db.Column(db.String(255), nullable=False, comment='Exchange Team')
    duration = db.Column(db.String(255), nullable=False, comment='Exchange Duration')
    start_date = db.Column(db.DateTime, nullable=False, comment='Exchange Start Date')
    end_date = db.Column(db.DateTime, nullable=False, comment='Exchange End Date')
    expert = db.Column(db.String(255), nullable=False, comment='Product Expert')
    maintenance = db.Column(db.String(255), nullable=False, comment='Maintenance Personnel')

    def __repr__(self):
        return f"<StaffInfo employee_id={self.employee_id}, name={self.name}>"

    def to_dict(self):
        """将模型实例转换为字典格式"""
        return {
            'id': self.id,
            'name': self.name,
            'gender': self.gender,
            'employee_id': self.employee_id,
            'id_card': self.id_card,
            'contact': self.contact,
            'dev_dept': self.dev_dept,
            'team': self.team,
            'duration': self.duration,
            'start_date': self.start_date.strftime('%Y-%m-%d %H:%M:%S') if self.start_date else None,
            'end_date': self.end_date.strftime('%Y-%m-%d %H:%M:%S') if self.end_date else None,
            'expert': self.expert,
            'maintenance': self.maintenance,
        }


# 一体化工作任务表
class IntegratedTask(db.Model):
    __tablename__ = 'integrated_task'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    integrated_work_id = db.Column(db.Integer, nullable=False, comment='一体化工作表ID')
    work_category = db.Column(db.String(255), nullable=False, comment='工作类别')
    work_subcategory = db.Column(db.String(255), nullable=False, comment='工作细类')
    work_item = db.Column(db.String(255), nullable=False, comment='工作项')
    work_task = db.Column(db.String(255), nullable=False, comment='工作任务')
    working_hours = db.Column(db.String(255), nullable=False, comment='工时')
    actual_work_content = db.Column(db.String(255), nullable=False, comment='实际工作内容')
    remarks = db.Column(db.String(255), nullable=False, comment='备注')
    create_time = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    update_time = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='修改时间')

    # create_time = db.Column(db.DateTime, nullable=False, comment='创建时间')
    # update_time = db.Column(db.DateTime, nullable=False, comment='修改时间')

    def to_dict(self):
        return {
            'id': self.id,
            'integrated_work_id': self.integrated_work_id,
            'work_category': self.work_category,
            'work_subcategory': self.work_subcategory,
            'work_item': self.work_item,
            'work_task': self.work_task,
            'working_hours': self.working_hours,
            'actual_work_content': self.actual_work_content,
            'remarks': self.remarks,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S') if self.create_time else None,
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S') if self.update_time else None,
        }

    def __repr__(self):
        return f"<IntegratedTask id={self.id} work_task={self.work_task}>"


# 一体化工作任务表文件属性
class IntegratedTaskFileAttribute(db.Model):
    __tablename__ = 'integrated_task_file_attribute'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    integrated_work_id = db.Column(BIGINT, nullable=False, comment='一体化工作表ID')
    file_name = db.Column(db.String(255), nullable=False, comment='一体化工作表文件名')
    app_abbreviation = db.Column(db.String(255), nullable=False, comment='应用简称')
    dev_department = db.Column(db.String(255), nullable=False, comment='开发部门')
    exchange_employee_id = db.Column(db.String(255), nullable=False, comment='交流员工号')
    exchange_employee_name = db.Column(db.String(255), nullable=False, comment='交流员工名字')
    work_period = db.Column(db.String(255), nullable=False, comment='一体化工作期数')
    create_time = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    update_time = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='修改时间')

    def to_dict(self):
        return {
            'id': self.id,
            'integrated_work_id': self.integrated_work_id,
            'file_name': self.file_name,
            'app_abbreviation': self.app_abbreviation,
            'dev_department': self.dev_department,
            'exchange_employee_id': self.exchange_employee_id,
            'exchange_employee_name': self.exchange_employee_name,
            'work_period': self.work_period,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S') if self.create_time else None,
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S') if self.update_time else None,
        }

    def __repr__(self):
        return f"<IntegratedTaskFileAttribute id={self.id} file_name={self.file_name}>"


# 一体化工作任务配置表
class IntegratedTaskConfig(db.Model):
    __tablename__ = 'integrated_task_config'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    work_category = db.Column(db.String(255), nullable=False, comment='工作类别')
    work_subcategory = db.Column(db.String(255), nullable=False, comment='工作细类')
    work_item = db.Column(db.String(255), nullable=False, comment='工作项')
    remarks = db.Column(db.String(255), nullable=False, comment='备注')
    create_time = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    update_time = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='修改时间')

    def to_dict(self):
        return {
            'id': self.id,
            'work_category': self.work_category,
            'work_subcategory': self.work_subcategory,
            'work_item': self.work_item,
            'remarks': self.remarks,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S') if self.create_time else None,
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S') if self.update_time else None,
        }

    def __repr__(self):
        return f"<IntegratedTaskConfig id={self.id} work_item={self.work_item}>"


# ------------------------------------------------
# 推送文件名称应用映射表
# ------------------------------------------------
class PatrolAppConfig(db.Model):
    __tablename__ = 't_patrol_app_config'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='序号')
    patrol_name = db.Column(db.String(100), nullable=False, comment='巡检名')
    app_name = db.Column(db.String(100), nullable=False, comment='应用名')
    match_alias = db.Column(db.String(100), nullable=False, comment='匹配别名字符')
    remark = db.Column(db.String(200), nullable=True, comment='备注')
    create_time = db.Column(db.DateTime, default=db.func.current_timestamp(), comment='创建时间')
    update_time = db.Column(db.DateTime, default=db.func.current_timestamp(),
                            onupdate=db.func.current_timestamp(), comment='更新时间')

    def __repr__(self):
        return f'<PatrolAppConfig id={self.id} patrol_name={self.patrol_name}>'

    def to_dict(self):
        return {
            'id': self.id,
            'patrol_name': self.patrol_name,
            'app_name': self.app_name,
            'match_alias': self.match_alias,
            'remark': self.remark,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S') if self.create_time else None,
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S') if self.update_time else None
        }


# ------------------------------------------------
# 巡检应用定义表
# ------------------------------------------------
class PatrolAppDef(db.Model):
    __tablename__ = 't_patrol_app_def'

    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='主键')
    app_name = db.Column(db.String(100), nullable=False, comment='应用中文名')
    app_name_short = db.Column(db.String(50), nullable=False, unique=True, comment='英文简称（唯一）')
    patrol_name = db.Column(db.JSON, nullable=True, comment='巡检配置名，存储巡检配置属组')
    app_type = db.Column(db.SmallInteger, nullable=False, default=1, comment='1业务 2中间件 3数据库 4基础设施')
    require_manual_patrol = db.Column(db.Boolean, nullable=False, default=False, comment='是否人工巡检')
    patrol_frequency = db.Column(db.String(50), nullable=True, comment='DAILY/WEEKLY/MONTHLY')
    manual_patrol_cycle = db.Column(db.Integer, nullable=True, comment='人工巡检周期（天）')
    responsible_person = db.Column(db.String(100), nullable=True, comment='负责人域账号')
    responsible_team = db.Column(db.String(100), nullable=True, comment='负责团队')
    contact_info = db.Column(db.String(200), nullable=True, comment='电话/邮箱/企微群')
    app_status = db.Column(db.Boolean, nullable=False, default=True, comment='0停用 1启用')
    config_params = db.Column(db.JSON, nullable=True, comment='JSON 扩展：URL、端口、阈值等')
    remark = db.Column(db.String(500), nullable=True, comment='备注')
    create_time = db.Column(db.DateTime, nullable=False, default=db.func.current_timestamp(), comment='创建时间')
    update_time = db.Column(db.DateTime, nullable=False, default=db.func.current_timestamp(),
                            onupdate=db.func.current_timestamp(), comment='更新时间')

    def __repr__(self):
        return f'<PatrolAppDef {self.app_name_short}>'

    def to_dict(self):
        return {
            'id': self.id,
            'app_name': self.app_name,
            'app_name_short': self.app_name_short,
            'patrol_name': self.patrol_name,
            'app_type': self.app_type,
            'require_manual_patrol': self.require_manual_patrol,
            'patrol_frequency': self.patrol_frequency,
            'manual_patrol_cycle': self.manual_patrol_cycle,
            'responsible_person': self.responsible_person,
            'responsible_team': self.responsible_team,
            'contact_info': self.contact_info,
            'app_status': self.app_status,
            'config_params': self.config_params,
            'remark': self.remark,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S') if self.create_time else None,
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S') if self.update_time else None
        }


